import CodeBlock from "@theme/CodeBlock";
import InMemoryExample from "@examples/embeddings/cache_backed_in_memory.ts";
import ConvexExample from "@examples/embeddings/convex/cache_backed_convex.ts";
import RedisExample from "@examples/embeddings/cache_backed_redis.ts";

# Caching

Embeddings can be stored or temporarily cached to avoid needing to recompute them.

Caching embeddings can be done using a `CacheBackedEmbeddings` instance.

The cache backed embedder is a wrapper around an embedder that caches embeddings in a key-value store.

The text is hashed and the hash is used as the key in the cache.

The main supported way to initialized a `CacheBackedEmbeddings` is the `fromBytesStore` static method. This takes in the following parameters:

- `underlying_embedder`: The embedder to use for embedding.
- `document_embedding_cache`: The cache to use for storing document embeddings.
- `namespace`: (optional, defaults to "") The namespace to use for document cache. This namespace is used to avoid collisions with other caches. For example, set it to the name of the embedding model used.

**Attention:** Be sure to set the namespace parameter to avoid collisions of the same text embedded using different embeddings models.

## Usage, in-memory

import IntegrationInstallTooltip from "@mdx_components/integration_install_tooltip.mdx";

<IntegrationInstallTooltip></IntegrationInstallTooltip>

```bash npm2yarn
npm install @langchain/openai @langchain/community
```

Here's a basic test example with an in memory cache. This type of cache is primarily useful for unit tests or prototyping.
Do not use this cache if you need to actually store the embeddings for an extended period of time:

<CodeBlock language="typescript">{InMemoryExample}</CodeBlock>

## Usage, Convex

Here's an example with a [Convex](https://convex.dev/) as a cache.

### Create project

Get a working [Convex](https://docs.convex.dev/) project set up, for example by using:

```bash
npm create convex@latest
```

### Add database accessors

Add query and mutation helpers to `convex/langchain/db.ts`:

```ts title="convex/langchain/db.ts"
export * from "langchain/util/convex";
```

### Configure your schema

Set up your schema (for indexing):

```ts title="convex/schema.ts"
import { defineSchema, defineTable } from "convex/server";
import { v } from "convex/values";

export default defineSchema({
  cache: defineTable({
    key: v.string(),
    value: v.any(),
  }).index("byKey", ["key"]),
});
```

### Example

<CodeBlock language="typescript">{ConvexExample}</CodeBlock>

## Usage, Redis

Here's an example with a Redis cache.

You'll first need to install `ioredis` as a peer dependency and pass in an initialized client:

```bash npm2yarn
npm install ioredis
```

<CodeBlock language="typescript">{RedisExample}</CodeBlock>
